package authentication.config.sharding.config.jdbc.v5_0_0.algorithms;

import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.replicaquery.spi.ReplicaLoadBalanceAlgorithm;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/4/26 上午9:21
 * @UpdateDate:
 * @Description:
 */
public class ExtendsLoadBalancerAlgorithm {

    public static class PerhapsLoadBalancerAlgorithm implements ReplicaLoadBalanceAlgorithm{

        private Map<String, AtomicInteger> CUSTOM = new ConcurrentHashMap<>();

        @Getter
        @Setter
        private Properties props = new Properties();

        @Override
        public String getDataSource(String name, String primaryDataSourceName, List<String> replicaDataSourceNames) {
            AtomicInteger current = CUSTOM.containsKey(name) ? CUSTOM.get(name) : new AtomicInteger(0);
            CUSTOM.putIfAbsent(name,current);
            current.compareAndSet(replicaDataSourceNames.size(),0);
            return replicaDataSourceNames.get(current.getAndIncrement() % replicaDataSourceNames.size());
        }

        @Override
        public String getType() {
            return "PERHAPS_LOAD_BALANCER_ROUND_ROBIN";
        }
    }


}
